﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace SocketTest
{
    internal class socketTCPServer
    {
       

        
    
        //创建一个socket的对象
        public static Socket socketServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        public static string serverIp = "127.0.0.1";//设定IP
        public static int serverPort = 8888;//设定端口
        public static byte[] result = new byte[1024];//定义一个字节数组,相当于缓存
        /// <summary>
        /// 创建socket服务
        /// </summary>
        public static void SocketServer()
        {
            IPAddress ip = IPAddress.Parse(serverIp);//服务器IP地址
            IPEndPoint point = new IPEndPoint(ip, serverPort);//获取端口
            socketServer.Bind(point);//绑定IP地址及端口
            socketServer.Listen(100);//开启监听并设定最多10个排队连接请求 
            Console.WriteLine("启动监听{0}成功", socketServer.LocalEndPoint.ToString());//输出启动成功提示

            Thread thread = new Thread(ListenSocket);//创建一个监听进程
            thread.Start();//运行
            Console.ReadLine();
        }
        /// <summary>
        /// 监听客户端连接
        /// </summary>
        public static void ListenSocket()
        {
            while (true)
            {
                Socket clientSocket = socketServer.Accept();//接收连接并返回一个新的Socket
                clientSocket.Send(Encoding.UTF8.GetBytes("服务器连接成功"));//在客户端显示"服务器连接成功"提示
                Thread recevieThread = new Thread(ReceiveMessage);//创建一个接受信息的进程
                recevieThread.Start(clientSocket);//运行新的Socket接受信息
            }
        }
        /// <summary>
        ///  接受Socket消息
        /// </summary>
        /// <param name="clientSocket"></param>
        public static void ReceiveMessage(object clientSocket)
        {
            Socket SocketClient = (Socket)clientSocket;
            while (true)
            {
                try
                {
                    //通过clientsocket接收数据
                    int num = SocketClient.Receive(result);//把接受到的数据存到bytes数组中并赋值给num
                    Console.WriteLine("接收客户端{0} 的消息：{1}", SocketClient.RemoteEndPoint.ToString(), Encoding.UTF8.GetString(result, 0, num));//GetString(result, 0, num)把从0到num的字节变成String
                    Thread.Sleep(1000);    //等待1秒钟  
                    //给SocketClient客户端返回信息
                    string sendMessage = "已成功接到socketServer发送的消息";//发送到客户端的内容
                    byte[] send = Encoding.UTF8.GetBytes(sendMessage);//Encoding.UTF8.GetBytes()将字符串转换成字节（避免乱码）
                    SocketClient.Send(send);//将接受成功的消息返回给SocketClient客户端
                    SocketClient.Close();//关闭Socket并释放资源
                }
                catch { }
            }
        }



    }
}
